package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    // 菜品
    @Autowired
    private DishService dishService;
    // 菜品口味
    @Autowired
    private DishFlavorService dishFlavorService;
    // 分页对象
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> List = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        List = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(List != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(List);
        }
        // //构造查询条件
        // LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        // //添加条件，查询状态为1（起售状态）的菜品
        // queryWrapper.eq(Dish::getStatus,1);
        // //添加排序条件
        // queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //
        // List<Dish> list = dishService.list(queryWrapper);
        //
        // return R.success(list);

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        //Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        //redisTemplate.delete(keys); //删除这些key
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    /**
     * 根据id查询菜品信息: 回显被修改的菜品数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 分页查询菜品信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        // 拼接分页查询的条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Dish::getName,name);
        // 分页查询
        dishService.page(pageInfo,wrapper);
        Page<DishDto> dishDtoPageInfo = new Page<>();
        // 完成对象中的数据拷贝, 参数1: 被拷贝的对象 参数2: 目标对象 参数3: 拷贝时忽略哪些字段不拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPageInfo,"records");
        // 获取当前页的记录
        List<Dish> dishList = pageInfo.getRecords();
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
//            DishDto dishDto = new DishDto();
//            dishDto.setName(dish.getName());
            // 将dish中的数据拷贝到dishdto中
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            // 封装分类的名称
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        dishDtoPageInfo.setRecords(dishDtoList);
        return R.success(dishDtoPageInfo);
    }

    /**
     * 添加菜品信息
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("添加菜品携带的数据: {}",dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        //Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        //redisTemplate.delete(keys); //删除这些key
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 停售启售-批量启售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids){
        //查询当前菜品是否有套餐在出售
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getDishId,ids);
        //获取含有此菜品的所有套餐
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
        //如果套餐存在
        if(setmealDishes != null && !setmealDishes.isEmpty()) {
            //获取套餐的id集合
            ArrayList<Long> idsList = new ArrayList<>();
            for (SetmealDish setmealDish : setmealDishes) {
                idsList.add(setmealDish.getSetmealId());
            }
            //查询套餐的停售状态
            LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(Setmeal::getId, idsList);
            wrapper1.eq(Setmeal::getStatus, 0);
            //统计含有菜品但处于停售状态的套餐数量
            int count = setmealService.count(wrapper1);
            //判断是否有套餐
            if (setmealDishes.size() > 0) {
                //判断当前含有此菜品的套餐既存在停售状态也存在启售状态
                if (setmealDishes.size() != count) {
                    //阻止停售操作
                    throw new CustomException("当前套餐中正在售出此菜品，无法停售");
                }
            }
        }
        LambdaQueryWrapper<Dish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(Dish::getId,ids);
        //获取所有id对应的菜品信息集合
        List<Dish> list = dishService.list(wrapper2);
        //List<Dish> list = dishService.listByIds(ids);
        //遍历菜品信息集合
        for (Dish dish : list) {
            //将每个菜品的状态设置为传入status的值
            dish.setStatus(status);
        }
        //批量更新
        dishService.updateBatchById(list);
        return R.success("更新成功");
    }


    /**
     * 删除-批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加条件，查询是否包含Id值
        wrapper.in(Dish::getId,ids);
        //添加条件，查询菜品状态是否为起售状态
        wrapper.eq(Dish::getStatus,1);
        //统计满足查询条件的记录数
        int count = dishService.count(wrapper);
        //如果记录数大于0，即存在有正在起售的菜品
        if(count>0){
            //抛出提示，提示无法删除
            throw new CustomException("菜品正在售卖中，无法删除");
        }
        //不存在起售的菜品，删除菜品信息
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }
}    